<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * crcl/base 2.x
 *
 * file MUST be included and loads autoloader (init())
 */

class _Base
{
  public static function init()
  {
    self::setIncludePath();

    spl_autoload_register(array('_Base', 'loadClass'));
  }

  /** PROTECTED ***********************************************************************************/

  /**
   * Default autoloader loader everything from /etc/lib
   * use namespace to define directories (PSR-0)
   * _ in file names are directories too
   * _ in namespaces have no special meaning
   *
   * /crcl/base/Database will be loaded from /etc/crcl/base/Database
   */
  protected static function loadClass($sClass)
  {
    $sClass = \ltrim($sClass, '\\');
    $sDirectory = \dirname(\dirname(\dirname(__FILE__))) . '/';

    $iLastNamespacePosition = \strripos($sClass, '\\');
    if ($iLastNamespacePosition !== \FALSE)
    {
      $sNamespace = \substr($sClass, 0, $iLastNamespacePosition);
      $sClass = \substr($sClass, $iLastNamespacePosition + 1);
      $sDirectory .= \str_replace('\\', '/', $sNamespace) . '/';
    }
    $sClass = \str_replace('_', '/', $sClass);
    $sClass = \str_replace('-', '_', $sClass);
    $sFile = $sClass . '.php';

    $sFile = $sDirectory . $sFile;
    include_once $sFile;
  }

  /** PRIVATE *************************************************************************************/

  private static function setIncludePath()
  {
    $sInclude = \ini_get('include_path');
    $sPath = \dirname(\dirname(\dirname(__FILE__))) . '/';

    if (\strpos($sInclude, $sPath) === \FALSE)
    {
      \ini_set('include_path', $sInclude . PATH_SEPARATOR . $sPath);
    }
  }
}

\_Base::init();